#include <dbg.h>

#include <cassert>

using namespace std;

class Solution {
public:
    int balancedString(string s) {
        int n = s.size();
        int m = n / 4;
        unordered_map<char, int> cnt;  // 记录每个字符出现的次数
        for (auto c : s) {
            ++cnt[c];
        }
        if (cnt['Q'] == m && cnt['W'] == m && cnt['E'] == m &&
            cnt['R'] == m) {  // 已经平衡
            return 0;
        }
        int res = n;
        int left = 0;
        for (int right = 0; right < n; ++right) {
            --cnt[s[right]];
            while (cnt['Q'] <= m && cnt['W'] <= m && cnt['E'] <= m &&
                   cnt['R'] <= m) {  // 窗口内的字符已经平衡
                res = min(res, right - left + 1);
                ++cnt[s[left]];
                ++left;
            }
        }
        return res;
    }
};

int main() {
    Solution s;

    assert(s.balancedString("QWER") == 0);
    assert(s.balancedString("QQWE") == 1);
    assert(s.balancedString("QQQW") == 2);
    assert(s.balancedString("QQQQ") == 3);

    return 0;
}